package com.demo.boot.filter;

import java.util.Enumeration;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.ehcache.CacheException;
import net.sf.ehcache.constructs.blocking.LockTimeoutException;
import net.sf.ehcache.constructs.web.AlreadyCommittedException;
import net.sf.ehcache.constructs.web.AlreadyGzippedException;
import net.sf.ehcache.constructs.web.filter.FilterNonReentrantException;
import net.sf.ehcache.constructs.web.filter.SimplePageCachingFilter;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
 
/**
 * <b>function:</b> mobile 页面缓存过滤器
 * @author hoojo
 * @createDate 2012-7-4 上午09:34:30
 * @file PageEhCacheFilter.java
 * @package com.hoo.ehcache.filter
 * @project Ehcache
 * @blog http://blog.csdn.net/IBM_hoojo
 * @email hoojo_@126.com
 * @version 1.0
 */
public class PageCachingFilter extends SimplePageCachingFilter {
 
	@Value("${ehcache.enablePageCache}")
	private boolean enablePageCache;
	
    private final static String FILTER_URL_PATTERNS = "excepts";
    private static String[] cacheURLs;
    
    private void init() throws CacheException {
        String patterns = filterConfig.getInitParameter(FILTER_URL_PATTERNS);
        if(patterns!=null){
        	cacheURLs = StringUtils.split(patterns,",");
        }
    }
    @Override
    protected void doFilter(final HttpServletRequest request,final HttpServletResponse response, final FilterChain chain) throws AlreadyGzippedException, AlreadyCommittedException,FilterNonReentrantException, LockTimeoutException, Exception {
    	if(enablePageCache){
    	   	if (cacheURLs == null) {
               	init();
           	}
           	String url = request.getRequestURI();
           	boolean flag = false;
           	if (cacheURLs != null && cacheURLs.length > 0) {
               	for (String cacheURL : cacheURLs) {
                   	if (url.contains(cacheURL.trim())) {
                       	flag = true;
                       	break;
                   	}
               	}
           	}
           	// 如果包含我们要缓存的url 就缓存该页面，否则执行正常的页面转向
           	if (flag) {
               	String query = request.getQueryString();
               	if (query != null) {
                   	query = "?" + query;
               	}
               	System.out.println("不能被缓存的请求已经被释放！URL:"+url);
               	chain.doFilter(request, response);
           	} else {
           		System.out.println("被缓存的请求：URL:"+url);
           		super.doFilter(request, response, chain);
           	}
       }else{
    		chain.doFilter(request, response);
       }
    }
    
    private boolean headerContains(final HttpServletRequest request, final String header, final String value) {
        logRequestHeaders(request);
        Enumeration<?> accepted = request.getHeaders(header);
        while (accepted.hasMoreElements()) {
            String headerValue = (String) accepted.nextElement();
            if (headerValue.indexOf(value) != -1) {
                return true;
            }
        }
        return false;
    }
    
    /**
     * @see net.sf.ehcache.constructs.web.filter.Filter#acceptsGzipEncoding(javax.servlet.http.HttpServletRequest)
     * <b>function:</b> 兼容ie6/7 gzip压缩
     * @author hoojo
     * @createDate 2012-7-4 上午11:07:11
     */
    @Override
    protected boolean acceptsGzipEncoding(HttpServletRequest request) {
    	boolean ie6 = headerContains(request, "User-Agent", "MSIE 6.0");
        boolean ie7 = headerContains(request, "User-Agent", "MSIE 7.0");
        return acceptsEncoding(request, "UTF-8") || ie6 || ie7;
    }
}